package org.threebitsoftware.tbb.Contact_GUI;

import java.sql.SQLException;

import org.apache.log4j.Logger;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Dialog;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.MenuItem;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.custom.CLabel;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Text;
import org.eclipse.swt.widgets.Label;
import com.swtdesigner.SWTResourceManager;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.widgets.Group;
import org.threebitsoftware.dao.generated.*;
import org.threebitsoftware.tbb.engine.EngineUtil;

public class UserProfileFormGUI extends Dialog {
	
	private static Logger logger = Logger.getLogger(UserProfileFormGUI.class);
	protected Object result_;
	protected Shell shlTbbUserProfile_;
	private Label lblLoginStatus ;
//	private String myAppUser= null;
	private static int usersLoginID_=-1; 
	private static String usernameLoginID_ = "";


	private Text usernameText_;
	private Text passwordText_;
	
	Button btnLogin_ = null;
	private boolean loginStatus_ = false;

	
	public static String getUsernameLoginID_() {
		return usernameLoginID_;
	}

	public static void setUsernameLoginID_(String usernameLoginID) {
		usernameLoginID_ = usernameLoginID;
	}
	
	
	public static int getUsersLoginID_() {
		return usersLoginID_;
	}

	public static void setUsersLoginID_(int usersLoginID) {
		usersLoginID_ = usersLoginID;
	}

	public boolean isLoginStatus() {
		return loginStatus_;
	}

	public void setLoginStatus(boolean loginStatus) {
		loginStatus_ = loginStatus;
	}

	public Text getUsernameText() {
		return usernameText_;
	}

	public void setUsernameText(Text usernameText) {
		this.usernameText_ = usernameText;
	}

	public Text getPasswordText() {
		return passwordText_;
	}

	public void setPasswordText(Text passwordText) {
		this.passwordText_ = passwordText;
	}

	public Button getBtnLogin() {
		return btnLogin_;
	}

	public void setBtnLogin(Button btnLogin) {
		this.btnLogin_ = btnLogin;
	}

	/**
	 * Create the dialog.
	 * 
	 * @param parent
	 * @param style
	 */
	public UserProfileFormGUI(Shell parent, int style) {
		super(parent, style);
		setText("SWT Dialog");
	 
	}

	
	/**
	 * Open the dialog.
	 * 
	 * @return the result
	 */
	public Object open() {
		createContents();
		shlTbbUserProfile_.open();
		shlTbbUserProfile_.layout();
		Display display = getParent().getDisplay();
		while (!shlTbbUserProfile_.isDisposed()) {

			if (!display.readAndDispatch()) {
				display.sleep();
			}
		}

		System.out.print("dispose");
		
		//if the loginstatus = true then credentials are right, else credentials are wrong.
		return result_;
	}

	/**
	 * Create contents of the dialog.
	 */
	private void createContents() {
		shlTbbUserProfile_ = new Shell(getParent(), SWT.DIALOG_TRIM | SWT.RESIZE);
		shlTbbUserProfile_.setBackground(SWTResourceManager
				.getColor(SWT.COLOR_WIDGET_BACKGROUND));
		shlTbbUserProfile_.setSize(450, 222);
		shlTbbUserProfile_.setText("TBB User Profile");
		{
			Label label = new Label(shlTbbUserProfile_, SWT.SEPARATOR
					| SWT.HORIZONTAL);
			label.setBounds(10, 23, 422, 6);
		}
		{
			CLabel lblUserProfileInformation = new CLabel(shlTbbUserProfile_,
					SWT.NONE);
			lblUserProfileInformation.setFont(SWTResourceManager.getFont(
					"Tahoma", 13, SWT.NORMAL));
			lblUserProfileInformation.setBounds(10, 0, 209, 29);
			lblUserProfileInformation.setText("User Profile Information");
		}
			
		{
			Group group = new Group(shlTbbUserProfile_, SWT.NONE);
			group.setBounds(10, 23, 422, 94);
			{
				usernameText_ = new Text(group, SWT.BORDER|SWT.SINGLE);
				usernameText_.setText(usernameLoginID_);
				
				if (usernameText_.getText().equals("")){//this is first time this window is open so enable the Username text box
					usernameText_.setEnabled(true);
					
				} else if (!usernameText_.getText().equals("")){//this is second time this window is open so disable the Username text box
					usernameText_.setEnabled(false);
				}
				usernameText_.addSelectionListener(new SelectionAdapter() {
					@Override
					public void widgetSelected(SelectionEvent e) {
					}
				});
				usernameText_.setBounds(94, 26, 185, 19);
			}
			{
				passwordText_ = new Text(group, SWT.BORDER|SWT.PASSWORD|SWT.SINGLE);
				passwordText_.addSelectionListener(new SelectionAdapter() {
					@Override
					public void widgetSelected(SelectionEvent e) {
					}
				});
				passwordText_.setBounds(94, 51, 185, 19);
			}
			{
				CLabel label = new CLabel(group, SWT.NONE);
				label.setBounds(10, 51, 78, 19);
				label.setText("Password:");
			}
			{
				CLabel label = new CLabel(group, SWT.NONE);
				label.setBounds(10, 26, 78, 19);
				label.setText("UserName: ");
			}
		}
		
		//LOGIN----------------------->
		{
			btnLogin_ = new Button(shlTbbUserProfile_, SWT.NONE);
			btnLogin_.addSelectionListener(new SelectionAdapter() {

				@Override
				public void widgetSelected(SelectionEvent e) {
					logger.info(usernameText_.getText() + " user logged in. ");
					System.out.println(usernameText_.getText() + " user logged in. ");

					// checks with the DB for the entered user. DB can respond
					// with
					// 1. true if entered information is right
					// 2. false if entered information is wrong.
					loginStatus_ = checkUserCredentials(usernameText_.getText(), passwordText_.getText());
					ContactFormGUI.setLoginStatus(loginStatus_);
					
					if (loginStatus_){//everything is Ok
						shlTbbUserProfile_.close();
					} else if (!loginStatus_){//credentials wrong or user does not exist
						lblLoginStatus.setVisible(true);
						logger.info("User "+ usernameText_.getText() +" does not exists or Credentials are wrong.");
						lblLoginStatus.setText("User "+ usernameText_.getText() +" does not exists or Credentials are wrong.");

					}
				
					
				}
			});
			btnLogin_.setBounds(363, 161, 68, 23);
			btnLogin_.setText("Login");

			// if the user is already logged in, the profile sub menu should not
			// have login button.
			if (loginStatus_ == true) {
				btnLogin_.setEnabled(false);
			}
		}
		
		//ADD-------------------------->
		{
			Button btnAdd = new Button(shlTbbUserProfile_, SWT.NONE);
			btnAdd.addSelectionListener(new SelectionAdapter() {
				@Override
				public void widgetSelected(SelectionEvent e) {
					System.out.println("Creating account for " + usernameText_.getText());
					
					boolean isUserExist = checkUserCredentials(usernameText_.getText(), passwordText_.getText());
					 if (isUserExist){
						 logger.info("User already exists. Choose another username");
						 System.out.println("User already exists. Choose another username");
							lblLoginStatus.setVisible(true);
							lblLoginStatus.setText("User "+ usernameText_.getText() +" already exists. Choose another username");
					 }
					 else if (!isUserExist){
						 System.out.println("Adding user " + usernameText_.getText());
						 try {
							EngineUtil.setIdAppUser(usernameText_.getText(), passwordText_.getText(), "insert");
							
							logger.info("Added new App user " + usernameText_.getText());
							System.out.println("Added new App user " + usernameText_.getText());
							
							ContactFormGUI.setLoginStatus(true);
							shlTbbUserProfile_.close();
						} catch (SQLException sqlInsertError) {
							
							logger.error("Error Inserting new App user account " + sqlInsertError.getMessage());
							System.out.println("Error Inserting new App user account.");
							
							lblLoginStatus.setVisible(true);
							lblLoginStatus.setText("Error during login.");
							sqlInsertError.printStackTrace();

						}
					 }
					
				}
			});

			btnAdd.setBounds(289, 161, 68, 23);
			btnAdd.setText("Add");

			// If the user is currently logged into the system. He should not be
			// able to add new account.
			// In order to add new account user needs to restart the
			// application.
			if (loginStatus_ == true) {
				btnAdd.setEnabled(false);
			}
		}
		
		//EDIT------------------------->
		{
			Button btnEdit = new Button(shlTbbUserProfile_, SWT.NONE);
			btnEdit.addSelectionListener(new SelectionAdapter() {
				@Override
				public void widgetSelected(SelectionEvent e) {
					System.out.println("Edit is clicked...");			
					try {
						usernameText_.setText(usernameLoginID_);
						usernameText_.setEnabled(false);
						EngineUtil.setIdAppUser(usernameText_.getText(), passwordText_.getText(),"update");

						logger.info("Updated account of App user " + usernameText_.getText());
						lblLoginStatus.setText("Updated account of App user " + usernameText_.getText());
						lblLoginStatus.setVisible(true);
						System.out.println("Updated App user " + usernameText_.getText());

					} catch (SQLException sqlUpdatedError) {
						logger.error("Error Updating new App user account " + sqlUpdatedError.getMessage());
						System.out.println("Error updating contact");
						lblLoginStatus.setVisible(true);
						lblLoginStatus.setText("Error during login.");
						sqlUpdatedError.printStackTrace();
					}
					
				}
			});
			btnEdit.setBounds(215, 161, 68, 23);
			btnEdit.setText("Edit");
			{
				lblLoginStatus = new Label(shlTbbUserProfile_, SWT.NONE);
				lblLoginStatus.setBounds(20, 123, 412, 23);
				lblLoginStatus.setText("Login Status");
				lblLoginStatus.setVisible(false);
			}

			// if user is logging in initially do not show the edit button. User
			// should be unable to edit his account
			// without logging in.
			if (loginStatus_ == false) {
				btnEdit.setEnabled(false);
			}
		}
		
	}

	/**
	 * check user credentials in DB and send status message.
	 * @param username
	 * @param password
	 * @return true: everything is OK  or false: Something is wrong
	 */
	public boolean checkUserCredentials(String username, String password) {

		AppUser loggedInAppUser = null;
		//Call the DB to get the user_id for the entered username and password
		try {
			loggedInAppUser = EngineUtil.getIdAppUser(username);
			
			usersLoginID_ = (int) loggedInAppUser.getIdAppUser();
			usernameLoginID_ = loggedInAppUser.getSUsername();
			
		} catch (SQLException sqlError) {

			System.out.println("Error getting Application User Info from Database.");
			lblLoginStatus.setVisible(true);
			lblLoginStatus.setText("Error during login.");
			sqlError.printStackTrace();
			
		} catch (NullPointerException appError){
			System.out.println("Error getting Application User Info from Database.");
			lblLoginStatus.setVisible(true);
			lblLoginStatus.setText("Error during login.");
			appError.printStackTrace();
		}

		if (usersLoginID_ == -1 ){
			
			//could not find user login
			loginStatus_ = false;
		}
		else if (usersLoginID_!=-1) {//found user login		
			
			if (loggedInAppUser.getSPassword().equals(password)){//password matches
				loginStatus_ = true;	
			} else if (!loggedInAppUser.getSPassword().equals(password)){//Error Password does not match
				loginStatus_ = false;	
			}
			
		}
		
		return loginStatus_;
	}
}
